import { useCallback, useEffect, useState } from "react";
import {
  Layout,
  C01Carousel,
  C22LoadingScreen,
  C02TileMenu,
} from "@/components";
import {
  useApplicationInfo,
  //getLoadingScreen,
} from "@/store/applicationDataContext";
import { downloadFiles } from "@/utils";

function Home() {
  const [preloadProgress, setPreloadProgress] = useState(0);
  const { applicationState } = useApplicationInfo();

  const [scrollTop, setScrollTop] = useState(0);

  useEffect(() => {
    if (applicationState.home) {
      const data = applicationState.home;

      const carouselFilesToPreload = data.homeBanner.map(
        (carouselData) => carouselData.video || carouselData.backImage
      );

      const tileFilesToPreload = data.homeDynamic.reduce(
        (accum, tileDataObj) => {
          const imageFilesArr = [tileDataObj.foreground];
          if (tileDataObj.background) {
            imageFilesArr.push(tileDataObj.background);
          }
          return [...accum, ...imageFilesArr];
        },
        []
      );

      const preloadFiles: string[] = [
        //...fontFiles,
        ...carouselFilesToPreload,
        ...tileFilesToPreload,
      ].filter((urlOrNull) => !!urlOrNull);

      downloadFiles(preloadFiles, (progress) => {
        setPreloadProgress(progress);
      });
    }
  }, [applicationState.home]);

  const scrollCb = useCallback((scrollTop) => setScrollTop(scrollTop), []);

  return (
    <Layout scrollCb={scrollCb}>
      {/* Need to have check against preloadProgress to ensure not triggering downloads due to added to DOM */}
      {preloadProgress === 1 && (
        <>
          {applicationState.home && applicationState.home.homeBanner && (
            <C01Carousel carouselItems={applicationState.home.homeBanner} />
          )}
          {applicationState.home && applicationState.home.homeDynamic && (
            <C02TileMenu
              tileMenuItems={applicationState.home.homeDynamic}
              scrollOffsetRaw={scrollTop}
            />
          )}
        </>
      )}
      {<C22LoadingScreen progress={preloadProgress} />}
    </Layout>
  );
}

export default Home;
